接續昨天進度,把最後發送訊息的函式給完成吧!
/// <summary>
/// 發送LineNotify通知
/// </summary>
/// <param name="condition"></param>
/// <returns></returns>
[WebMethod(EnableSession = true)]
public ServiceResultStruct<bool> SendLineNotifyByAlarmSysId(string jsonArray)
{
//宣告各項變數
var condition = JsonDeserialize(jsonArray); //接收傳入值
var token = "填入所申請的權杖"; // 參考Day16章節
var result = new ServiceResultStruct<bool>(); //回傳值
var message = string.Empty; //發送訊息
var stickerPackageId = string.Empty; //Line貼圖類別
var stickerId = string.Empty; //Line貼圖編號
//判斷傳入的參數是否有值
if (condition.ContainsKey("message"))
{
message = condition["message"].ToString();
}
if (condition.ContainsKey("stickerpackageid"))
{
stickerPackageId = condition["stickerpackageid"].ToString();
}
if (condition.ContainsKey("stickerid"))
{
stickerId = condition["stickerid"].ToString();
}
//使用WebClient發送訊息
using (var wc = new WebClient())
{
//安全性通訊協定,指定 Transport Layer Security (TLS) 1.2 安全性通訊協定
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
//指定Token(所申請的權杖)
var bearer = token;
//宣告編碼為UTF8,並填入指定Token到傳輸參數內
wc.Encoding = Encoding.UTF8;
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.Headers.Add("Authorization", $"Bearer {bearer}");
//宣告NameValueCollection()集合類別,用來儲存字串集合
var nv = new NameValueCollection();
nv["message"] = message; //訊息文字
nv["stickerPackageId"] = stickerPackageId; //貼圖類別
nv["stickerId"] = stickerId; //貼圖編號
//指定Line API網址並發送訊息
var bResult = wc.UploadValues($"https://notify-api.line.me/api/notify", nv);
//取得執行後回傳結果
var res = Encoding.UTF8.GetString(bResult);
//回傳結果宣告為JSON
var resultjson = JsonDeserialize(res);
if (resultjson.ContainsKey("status") && Convert.ToInt16(resultjson["status"]) == (byte)EHttpCodeType.成功)
{
result.Result = true;
result.ErrMsg = string.Empty;
result.Memo = "發送完成";
result.HttpCode = EHttpCodeType.成功;
result.Status = true;
}
else
{
result.Result = false;
result.ErrMsg = resultjson["message"];
result.Memo = "發送失敗";
result.HttpCode = EHttpCodeType.伺服器端程序錯誤;
result.Status = true;
}
}
return result;
}
如此一來就完成整個後台專案啦!
好的,今天就先到這兒,明天再來繼續吧!